import React, { useState, useEffect } from 'react';
import {
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
  Typography,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
  Pagination,
  Alert,
  CircularProgress,
  Tooltip,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from '@mui/material';
import { Refresh, Visibility } from '@mui/icons-material';
import { useContent } from '../../../hooks';
import { OperationLog, OperationType, OperationStatus } from '../../../types';
import { formatDateTime, getOperationColor } from '../../../utils';

const ContentOperationLogs: React.FC = () => {
  const { getOperationLogs, loading, error } = useContent();
  const [logs, setLogs] = useState<OperationLog[]>([]);
  const [total, setTotal] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(20);
  
  // 筛选条件
  const [operationType, setOperationType] = useState<string>('all');
  const [contentId, setContentId] = useState<string>('');
  
  // 详情对话框
  const [selectedLog, setSelectedLog] = useState<OperationLog | null>(null);
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);

  // 加载日志数据
  const loadLogs = async (page = currentPage) => {
    try {
      const params = {
        page,
        size: pageSize,
        operationType: operationType !== 'all' ? operationType : undefined,
        contentId: contentId ? parseInt(contentId) : undefined,
      };
      
      const response = await getOperationLogs(params);
      setLogs(response.logs);
      setTotal(response.total);
      setTotalPages(response.totalPages);
      setCurrentPage(response.pageNum);
    } catch (err) {
      console.error('加载操作日志失败:', err);
    }
  };

  // 初始加载
  useEffect(() => {
    loadLogs(1);
  }, []);

  // 筛选条件变化时重新加载
  const handleFilter = () => {
    setCurrentPage(1);
    loadLogs(1);
  };

  // 重置筛选条件
  const handleReset = () => {
    setOperationType('all');
    setContentId('');
    setCurrentPage(1);
    loadLogs(1);
  };

  // 页码变化
  const handlePageChange = (event: React.ChangeEvent<unknown>, page: number) => {
    setCurrentPage(page);
    loadLogs(page);
  };

  // 查看详情
  const handleViewDetail = (log: OperationLog) => {
    setSelectedLog(log);
    setDetailDialogOpen(true);
  };

  // 格式化操作类型显示
  const formatOperationType = (type: OperationType): string => {
    const typeMap: Record<OperationType, string> = {
      [OperationType.UPLOAD_IMAGES]: '上传图片',
      [OperationType.UPLOAD_VIDEO]: '上传视频',
      [OperationType.UPLOAD_COVER]: '上传封面',
      [OperationType.UPDATE_IMAGES]: '更新图片',
      [OperationType.UPDATE_VIDEO]: '更新视频',
      [OperationType.UPDATE_COVER]: '更新封面',
    };
    return typeMap[type] || type;
  };

  // 格式化操作状态显示
  const formatOperationStatus = (status: OperationStatus): string => {
    const statusMap: Record<OperationStatus, string> = {
      [OperationStatus.PENDING]: '等待中',
      [OperationStatus.IN_PROGRESS]: '进行中',
      [OperationStatus.COMPLETED]: '已完成',
      [OperationStatus.FAILED]: '失败',
    };
    return statusMap[status] || status;
  };

  // 获取状态颜色
  const getStatusColor = (status: OperationStatus): 'default' | 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' => {
    switch (status) {
      case OperationStatus.COMPLETED:
        return 'success';
      case OperationStatus.FAILED:
        return 'error';
      case OperationStatus.IN_PROGRESS:
        return 'primary';
      case OperationStatus.PENDING:
        return 'warning';
      default:
        return 'default';
    }
  };

  if (loading && logs.length === 0) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box>
      {/* 筛选条件 */}
      <Box sx={{ mb: 3, display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
        <FormControl size="small" sx={{ minWidth: 150 }}>
          <InputLabel>操作类型</InputLabel>
          <Select
            value={operationType}
            label="操作类型"
            onChange={(e) => setOperationType(e.target.value)}
          >
            <MenuItem value="all">全部</MenuItem>
            <MenuItem value={OperationType.UPLOAD_IMAGES}>上传图片</MenuItem>
            <MenuItem value={OperationType.UPLOAD_VIDEO}>上传视频</MenuItem>
            <MenuItem value={OperationType.UPLOAD_COVER}>上传封面</MenuItem>
            <MenuItem value={OperationType.UPDATE_IMAGES}>更新图片</MenuItem>
            <MenuItem value={OperationType.UPDATE_VIDEO}>更新视频</MenuItem>
            <MenuItem value={OperationType.UPDATE_COVER}>更新封面</MenuItem>
          </Select>
        </FormControl>

        <TextField
          size="small"
          label="内容ID"
          value={contentId}
          onChange={(e) => setContentId(e.target.value)}
          type="number"
          sx={{ width: 120 }}
        />

        <Button variant="contained" onClick={handleFilter} disabled={loading}>
          筛选
        </Button>
        <Button variant="outlined" onClick={handleReset} disabled={loading}>
          重置
        </Button>
        <IconButton onClick={() => loadLogs(currentPage)} disabled={loading}>
          <Refresh />
        </IconButton>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      {/* 统计信息 */}
      <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
        共 {total} 条记录，第 {currentPage} / {totalPages} 页
      </Typography>

      {/* 日志表格 */}
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>ID</TableCell>
              <TableCell>内容ID</TableCell>
              <TableCell>操作类型</TableCell>
              <TableCell>状态</TableCell>
              <TableCell>进度</TableCell>
              <TableCell>开始时间</TableCell>
              <TableCell>完成时间</TableCell>
              <TableCell>操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {logs.map((log) => (
              <TableRow key={log.id} hover>
                <TableCell>{log.id}</TableCell>
                <TableCell>{log.contentId}</TableCell>
                <TableCell>
                  <Chip
                    label={formatOperationType(log.operationType)}
                    color={getOperationColor(formatOperationType(log.operationType)) as any}
                    size="small"
                  />
                </TableCell>
                <TableCell>
                  <Chip
                    label={formatOperationStatus(log.operationStatus)}
                    color={getStatusColor(log.operationStatus)}
                    size="small"
                  />
                </TableCell>
                <TableCell>
                  {log.totalOperations > 0 && (
                    <Tooltip title={`${log.completedOperations}/${log.totalOperations} 完成${log.failedOperations ? `，${log.failedOperations} 失败` : ''}`}>
                      <Typography variant="body2">
                        {Math.round((log.completedOperations / log.totalOperations) * 100)}%
                      </Typography>
                    </Tooltip>
                  )}
                </TableCell>
                <TableCell>
                  <Typography variant="body2">
                    {formatDateTime(log.startedAt)}
                  </Typography>
                </TableCell>
                <TableCell>
                  <Typography variant="body2">
                    {log.completedAt ? formatDateTime(log.completedAt) : '-'}
                  </Typography>
                </TableCell>
                <TableCell>
                  <IconButton size="small" onClick={() => handleViewDetail(log)}>
                    <Visibility />
                  </IconButton>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* 分页 */}
      {totalPages > 1 && (
        <Box sx={{ mt: 3, display: 'flex', justifyContent: 'center' }}>
          <Pagination
            count={totalPages}
            page={currentPage}
            onChange={handlePageChange}
            color="primary"
            disabled={loading}
          />
        </Box>
      )}

      {/* 详情对话框 */}
      <Dialog
        open={detailDialogOpen}
        onClose={() => setDetailDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>操作日志详情</DialogTitle>
        <DialogContent>
          {selectedLog && (
            <Box sx={{ py: 1 }}>
              <Typography variant="body2" sx={{ mb: 1 }}>
                <strong>ID:</strong> {selectedLog.id}
              </Typography>
              <Typography variant="body2" sx={{ mb: 1 }}>
                <strong>内容ID:</strong> {selectedLog.contentId}
              </Typography>
              <Typography variant="body2" sx={{ mb: 1 }}>
                <strong>操作类型:</strong> {formatOperationType(selectedLog.operationType)}
              </Typography>
              <Typography variant="body2" sx={{ mb: 1 }}>
                <strong>操作状态:</strong> {formatOperationStatus(selectedLog.operationStatus)}
              </Typography>
              <Typography variant="body2" sx={{ mb: 1 }}>
                <strong>总操作数:</strong> {selectedLog.totalOperations}
              </Typography>
              <Typography variant="body2" sx={{ mb: 1 }}>
                <strong>已完成:</strong> {selectedLog.completedOperations}
              </Typography>
              {selectedLog.failedOperations && (
                <Typography variant="body2" sx={{ mb: 1 }}>
                  <strong>失败数:</strong> {selectedLog.failedOperations}
                </Typography>
              )}
              <Typography variant="body2" sx={{ mb: 1 }}>
                <strong>开始时间:</strong> {formatDateTime(selectedLog.startedAt)}
              </Typography>
              {selectedLog.completedAt && (
                <Typography variant="body2" sx={{ mb: 1 }}>
                  <strong>完成时间:</strong> {formatDateTime(selectedLog.completedAt)}
                </Typography>
              )}
              <Typography variant="body2" sx={{ mb: 1 }}>
                <strong>创建者ID:</strong> {selectedLog.createdBy}
              </Typography>
              {selectedLog.errorMessage && (
                <Box sx={{ mt: 2 }}>
                  <Typography variant="body2" sx={{ mb: 1 }}>
                    <strong>错误信息:</strong>
                  </Typography>
                  <Paper sx={{ p: 2, bgcolor: 'error.light', color: 'error.contrastText' }}>
                    <Typography variant="body2" component="pre" sx={{ whiteSpace: 'pre-wrap' }}>
                      {selectedLog.errorMessage}
                    </Typography>
                  </Paper>
                </Box>
              )}
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDetailDialogOpen(false)}>关闭</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default ContentOperationLogs; 